<template>
  <div class="register">
    <el-form
      :model="registerForm"
      :rules="registerRules"
      ref="registerForm"
      label-width="auto"
      class="register-form"
      size="small"
      status-icon
    >
      <h2>ESDN注册</h2>
      <el-form-item prop="userId">
        <el-input
          type="text"
          v-model="registerForm.userId"
          placeholder="请输入工号"
          clearable
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="mobile">
        <el-input
          type="text"
          v-model="registerForm.mobile"
          clearable
          placeholder="请输入手机号"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="username">
        <el-input
          type="text"
          v-model="registerForm.username"
          clearable
          placeholder="请输入姓名"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="sector">
        <span>部门：</span>
        <el-select v-model="registerForm.sector" placeholder="请选择部门">
          <el-option
            v-for="item in sectors"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          type="password"
          v-model="registerForm.password"
          clearable
          placeholder="请输入密码"
        ></el-input>
        <span
          style="float: right; font-weight: bold; color: red"
          v-if="passwordFlag >= 3"
          >极强</span
        >
        <span
          style="float: right; font-weight: bold; color: brown"
          v-if="passwordFlag === 2"
          >中等</span
        >
        <span
          style="float: right; font-weight: bold; color: brown"
          v-if="passwordFlag === 1"
          >极弱</span
        >
      </el-form-item>
      <el-form-item prop="checkpass">
        <el-input
          type="password"
          v-model="registerForm.checkpass"
          clearable
          placeholder="再次确认密码"
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          class="registerSubmit"
          style="float: left; margin-left: 50px"
          type="primary"
          @click="submitForm('registerForm')"
          >注册</el-button
        >
        <el-button
          class="gobackLogin"
          style="float: right; margin-right: 50px"
          @click="returnForm"
          >返回登录</el-button
        >
      </el-form-item>
    </el-form>
    <!--底部-->
    <div class="el-login-footer">
      <span>ESDN欢迎你的到来</span>
    </div>
  </div>
</template>
<script>
import {postRegisterFormData,getDeptNameList} from "@/api/login/login";
export default {
  data() {
    // 工号检验
    var validateUser = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入工号"));
      } else {
        //后续可添加工号检验逻辑
        // 是否数字检验
        if (!/^[0-9]*$/.test(this.registerForm.userId)) {
          callback(new Error("请输入正确的工号"));
        }
        callback();
      }
    };
    // 手机号码检验
    var validateMobile = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号码不能为空"));
      } else {
        var regMobile =
          /^(13[0-9]{9})|(15[0-9]{9})|(17[0-9]{9})|(18[0-9]{9})|(19[0-9]{9})$/;
        if (!regMobile.test(this.registerForm.mobile)) {
          callback(new Error("手机号码格式错误"));
          this.registerForm.mobile = "";
        }
        callback();
      }
    };
    // 姓名校验
    var validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("姓名不能为空"));
      } else {
        let regUsername =
          /^[\u4E00-\u9FA5]{2,10}(·[\u4E00-\u9FA5]{2,10}){0,2}$/;
        if (!regUsername.test(this.registerForm.username)) {
          callback(new Error("请输入正确的用户姓名"));
          this.registerForm.username = "";
        }
        callback();
      }
    };
    // 密码检验
    var validatePassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("密码不能为空"));
      } else {
        var lv = 0;
        if (/[a-z]/g.test(this.registerForm.password)) {
          lv++;
        } //验证是否包含字母
        if (/[0-9]/g.test(this.registerForm.password)) {
          lv++;
        } // 验证是否包含数字
        if (/(.[^a-z0-9])/g.test(this.registerForm.password)) {
          lv++;
        } //验证是否包含字母，数字，字符
        if (this.registerForm.password.length < 6) {
          lv = 0;
        } //如果密码长度小于6位，提示消息为空
        if (lv < 3) {
          callback(
            new Error("请输入带字母，数字，特殊字符且长度大于6位的强密码")
          );
          this.registerForm.password = "";
        }
        callback();
      }
    };
    // 确认密码
    var validateCheckpass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else {
        if (value !== this.registerForm.password) {
          callback(new Error("两次密码不一致"));
          this.registerForm.checkpass = "";
        }
        callback();
      }
    };
    return {
      passwordFlag: "", ///密码强弱检验
      sectors: ["部门一", "部门二", "其他分类"], //创建时获取部门数据
      registerForm: {
        userId: "",
        mobile: "",
        username: "",
        sector: "",
        password: "",
        checkpass: "",
      },
      registerRules: {
        userId: [
          {
            required: true,
            trigger: "blur",
            validator: validateUser,
          },
        ],
        mobile: [
          {
            required: true,
            trigger: "blur",
            validator: validateMobile,
          },
        ],
        username: [
          {
            required: true,
            trigger: "blur",
            validator: validateUsername,
          },
        ],
        sector: [
          {
            required: true,
            trigger: "change",
            message: "请选择部门",
          },
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            validator: validatePassword,
          },
        ],
        checkpass: [
          {
            required: true,
            trigger: "blur",
            validator: validateCheckpass,
          },
        ],
      },
    };
  },
  methods: {
    returnForm() {
      // 返回login界面
      this.$router.push("/");
    },
    submitForm(formName) {
      // 注册事件
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          console.log("error submit!!");
          return false;
        } else {
          // 数据对接处理
          let formData = {
            userId: parseInt(this.registerForm.userId),
            password: this.registerForm.password,
            phonenumber: this.registerForm.mobile,
            userName: this.registerForm.username,
            deptName: this.registerForm.sector,
          };
          let data = JSON.stringify(formData);
          console.log(data);
          // 对服务器上传数据
         postRegisterFormData(data)
            .then((res) => {
              // 提交成功处理
              console.log(res);
              // 注册成功与否弹出框
              if (res.code === 200) {
                let str =
                  "恭喜您的账号已成功注册！您目前以未认证状态登入网站，待部门负责人通过审批后您方可成为部门认证员工浏览部门文件。";
                this.$alert(str, "", {
                  confirmButtonText: "返回登录",
                  customClass: "checkMessageBox",
                }).then(() => {
                  this.$router.push("/");
                });
              } else {
                let str = "您的工号或手机号已经注册，请去找回密码";
                this.$confirm(str, "", {
                  confirmButtonText: "找回密码",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                  .then(() => {
                    this.$router.push("/findPassword");
                  })
                  .catch(() => {});
              }
            })
            .catch((err) => {
              // 提交失败处理
              console.log(err);
            });
        }
      });
    },
  },
  watch: {
    registerForm: {
      deep: true,
      handler(newval) {
        var lv = 0;
        if (/[a-z]/g.test(newval.password)) {
          lv++;
        } //验证是否包含字母
        if (/[0-9]/g.test(newval.password)) {
          lv++;
        } // 验证是否包含数字
        if (/(.[^a-z0-9])/g.test(newval.password)) {
          lv++;
        } //验证是否包含字母，数字，字符
        if (newval.password.length < 6) {
          lv = 0;
        } //如果密码长度小于6位，提示消息为空
        this.passwordFlag = lv;
      },
    },
  },
  created() {
    // 创建时获取部门列表数据
    getDeptNameList().then((res) => {
      console.log(res);
      this.sectors = [];
      for (let i in res.data) {
        this.sectors.push(res.data[i]);
      }
    });
  },
};
</script>
<style scoped>
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 50px;
  height: 100%;
  background-size: cover;
}

.register-form {
  border-radius: 15px;
  border: 1px solid rgb(85, 85, 85);
  width: 400px;
  text-align: center;
  font-size: 15px;
  padding: 25px 25px 25px 25px;
}

.el-form-item {
  margin-top: 30px;
  width: 400px;
  text-align: center;
}

.el-input {
  width: 70%;
}

.el-button {
  width: 80px;
  height: 30px;
  margin: -2px auto;
  border-radius: 5px;
  background-color: rgb(2, 167, 240);
  text-align: center;
  color: #fefefe;
  border: 2px solid #a9a9a9;
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: black;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style>

<style>
.el-form-item__error {
  margin-left: 60px;
}
</style>
